'''
Created on Apr 20, 2011

@author: riche
'''

from ft.framework import application, connector, abstraction
from ft.framework.file_io import file_reader, file_writer
from ft.apps.webserver import server, constants, login
import sys

class ServerApp(application.Application):
    
    def __init__(self, server_type):
        application.Application.__init__(self)
        fr = file_reader.FileReaderComponent(constants.d_path('CLIENT_IN_LR.txt'), 'reader')
        fw = file_writer.FileWriterComponent(constants.d_path('CLIENT_OUT_LR.txt'))
        sa = None
        if server_type == 'normal':
            sa = LoginServerAbs('Server_alg0')
        elif server_type == 'mr':
            sa = LoginMRServerAbs('Server_alg0')
        self.add_components([fr, fw, sa])
        fr_sa = connector.Connector(fr.get_output_endpoint(), sa.get_endpoint('incoming'))
        sa_fw = connector.Connector(sa.get_endpoint('outgoing'), fw.get_input_endpoint())
        self.add_connections([fr_sa, sa_fw])
        self.resolve_abstractions()
        self.instrument(constants.d_path(''), 'LR')
        
class LoginMRServerAbs(abstraction.Abstraction):
    
    def __init__(self, name):
        abstraction.Abstraction.__init__(self, name)
        sa = server.MRServerAbs('Server_alg0')
        self.add_component(sa)
        lg = login.LoginComp('Login_alg1')
        self.add_component(lg)
        self.add_port('incoming', (lg, 'in'))
        self.add_port('outgoing', (sa, 'outgoing'), True)
        lg_outgoing = connector.Connector(lg.get_endpoint('error'), self.get_endpoint('outgoing'))
        self.add_connector(lg_outgoing)
        lg_sa = connector.Connector(lg.get_endpoint('pass_through'), sa.get_endpoint('incoming'))
        self.add_connector(lg_sa)
        
class LoginServerAbs(abstraction.Abstraction):
    
    def __init__(self, name):
        abstraction.Abstraction.__init__(self, name)
        sa = server.ServerAbs('Server_alg0')
        self.add_component(sa)
        lg = login.LoginComp('Login_alg1')
        self.add_component(lg)
        self.add_port('incoming', (lg, 'in'))
        self.add_port('outgoing', (sa, 'outgoing'), True)
        lg_outgoing = connector.Connector(lg.get_endpoint('error'), self.get_endpoint('outgoing'))
        self.add_connector(lg_outgoing)
        lg_sa = connector.Connector(lg.get_endpoint('pass_through'), sa.get_endpoint('incoming'))
        self.add_connector(lg_sa)
        
if __name__ == '__main__':
    app = None
    if len(sys.argv) > 1:
        app = ServerApp(sys.argv[1])
    else:
        app = ServerApp('normal')
    app.execute(True, .5)